package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.CollectionFolders;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.CollectionFoldersService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 收藏夹接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/collection-folders")
@Slf4j
public class CollectionFoldersController {

    @Resource
    private CollectionFoldersService collectionFoldersService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建收藏夹
     *
     * @param collectionFolders
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCollectionFolder(@RequestBody CollectionFolders collectionFolders, HttpServletRequest request) {
        if (collectionFolders == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        collectionFolders.setUser_id(loginUser.getId());
        
        // 检查同一用户下收藏夹名称是否重复
        CollectionFolders existingFolder = collectionFoldersService.lambdaQuery()
                .eq(CollectionFolders::getUser_id, loginUser.getId())
                .eq(CollectionFolders::getName, collectionFolders.getName())
                .one();
        if (existingFolder != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "收藏夹名称已存在");
        }
        
        boolean result = collectionFoldersService.save(collectionFolders);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCollectionFolderId = collectionFolders.getId();
        return ResultUtils.success(newCollectionFolderId);
    }

    /**
     * 删除收藏夹
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCollectionFolder(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        CollectionFolders oldCollectionFolder = collectionFoldersService.getById(id);
        ThrowUtils.throwIf(oldCollectionFolder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCollectionFolder.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = collectionFoldersService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新收藏夹
     *
     * @param collectionFolders
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateCollectionFolder(@RequestBody CollectionFolders collectionFolders, HttpServletRequest request) {
        if (collectionFolders == null || collectionFolders.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        // 判断是否存在
        CollectionFolders oldCollectionFolder = collectionFoldersService.getById(collectionFolders.getId());
        ThrowUtils.throwIf(oldCollectionFolder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCollectionFolder.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        
        // 检查同一用户下收藏夹名称是否重复（排除自己）
        if (collectionFolders.getName() != null && !collectionFolders.getName().equals(oldCollectionFolder.getName())) {
            CollectionFolders existingFolder = collectionFoldersService.lambdaQuery()
                    .eq(CollectionFolders::getUser_id, user.getId())
                    .eq(CollectionFolders::getName, collectionFolders.getName())
                    .ne(CollectionFolders::getId, collectionFolders.getId())
                    .one();
            if (existingFolder != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "收藏夹名称已存在");
            }
        }
        
        boolean result = collectionFoldersService.updateById(collectionFolders);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取收藏夹
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<CollectionFolders> getCollectionFolderById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CollectionFolders collectionFolder = collectionFoldersService.getById(id);
        if (collectionFolder == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        User user = userService.getLoginUser(request);
        // 检查权限：只有收藏夹所有者、管理员或公开收藏夹可以查看
        if (!collectionFolder.getUser_id().equals(user.getId()) 
            && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        
        return ResultUtils.success(collectionFolder);
    }

    /**
     * 分页获取当前用户的收藏夹列表
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/my")
    public BaseResponse<Page<CollectionFolders>> listMyCollectionFolders(
            @RequestParam long current, 
            @RequestParam long size,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Page<CollectionFolders> collectionFolderPage = collectionFoldersService.lambdaQuery()
                .eq(CollectionFolders::getUser_id, loginUser.getId())
                .orderByDesc(CollectionFolders::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(collectionFolderPage);
    }

    /**
     * 分页获取收藏夹列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<CollectionFolders>> listCollectionFolderByPage(@RequestParam long current, @RequestParam long size) {
        Page<CollectionFolders> collectionFolderPage = collectionFoldersService.page(new Page<>(current, size));
        return ResultUtils.success(collectionFolderPage);
    }

    /**
     * 根据用户ID获取收藏夹列表
     *
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-user")
    public BaseResponse<Page<CollectionFolders>> getCollectionFoldersByUserId(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            HttpServletRequest request) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        Page<CollectionFolders> collectionFolderPage;
        
        // 如果是查看自己的收藏夹或者是管理员，可以看到所有收藏夹
        if (userId.equals(loginUser.getId()) || userService.isAdmin(request)) {
            collectionFolderPage = collectionFoldersService.lambdaQuery()
                    .eq(CollectionFolders::getUser_id, userId)
                    .orderByDesc(CollectionFolders::getCreated_at)
                    .page(new Page<>(current, size));
        } else {
            // 否则只能看到公开的收藏夹
            collectionFolderPage = collectionFoldersService.lambdaQuery()
                    .eq(CollectionFolders::getUser_id, userId)
//                    .eq(CollectionFolders::getVisibility, "public")
                    .orderByDesc(CollectionFolders::getCreated_at)
                    .page(new Page<>(current, size));
        }
        
        return ResultUtils.success(collectionFolderPage);
    }

    /**
     * 搜索收藏夹
     *
     * @param keyword
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<Page<CollectionFolders>> searchCollectionFolders(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            HttpServletRequest request) {
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        Page<CollectionFolders> collectionFolderPage;
        
        // 管理员可以搜索所有收藏夹
        if (userService.isAdmin(request)) {
            collectionFolderPage = collectionFoldersService.lambdaQuery()
                    .like(CollectionFolders::getName, keyword)
                    .or()
                    .like(CollectionFolders::getDescription, keyword)
                    .orderByDesc(CollectionFolders::getCreated_at)
                    .page(new Page<>(current, size));
        } else {
            // 普通用户只能搜索自己的收藏夹和公开的收藏夹
            collectionFolderPage = collectionFoldersService.lambdaQuery()
                    .and(wrapper -> wrapper
                            .like(CollectionFolders::getName, keyword)
                            .or()
                            .like(CollectionFolders::getDescription, keyword)
                    )
                    .and(wrapper -> wrapper
                            .eq(CollectionFolders::getUser_id, loginUser.getId())
                            .or()
//                            .eq(CollectionFolders::getVisibility, "public")
                    )
                    .orderByDesc(CollectionFolders::getCreated_at)
                    .page(new Page<>(current, size));
        }
        
        return ResultUtils.success(collectionFolderPage);
    }

    /**
     * 更新收藏夹可见性
     *
     * @param id
     * @param visibility
     * @param request
     * @return
     */
    @PostMapping("/update/visibility")
    public BaseResponse<Boolean> updateCollectionFolderVisibility(
            @RequestParam Long id,
            @RequestParam String visibility,
            HttpServletRequest request) {
        if (id == null || id <= 0 || visibility == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User user = userService.getLoginUser(request);
        CollectionFolders collectionFolder = collectionFoldersService.getById(id);
        ThrowUtils.throwIf(collectionFolder == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 仅本人或管理员可修改
        if (!collectionFolder.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        
//        collectionFolder.setVisibility(visibility);
        boolean result = collectionFoldersService.updateById(collectionFolder);
        return ResultUtils.success(result);
    }

}